<?php
/**
 * Created by b17
 * 2/15/12 5:22 PM
 */

class Admin_DeliveryController extends G4T_CrudController
{

    public function indexAction()
    {
        $emails = $this->manager->getList();
        $this->view->emails = $emails;
    }

    /**
     * Возвращает менеджер для работы с сущностью.
     *
     * @return \Managers\CrudManager
     */
    protected function getManager()
    {
        return new \Managers\DeliveryEmail();
    }

    /**
     * Возвращает строителя форм для создания форм.
     * @return \G4T\Form\FormBuilder
     */
    protected function createFormBuilder()
    {
        $formBuilder = \G4T\Form\FormBuilder::createFormBuilder(\Managers\DeliveryEmail::TABLE)
            ->addField('email', 'email', array('label' => 'Email', 'class' => 'text-input medium-input'))
            ->addField('token', 'hash')
            ->addField('sumbit', 'submit', array('label' => 'Save', 'class' => 'btn btn-primary'));
        return $formBuilder;
    }

    /**
     * Переход при не найденой сущности.
     * @param $id
     */
    protected function redirectWhenNotFound($id = null)
    {
        $this->_flashMessenger->addMessage('Record not found.', Lib_Flash::ERROR, Lib_Flash::LATER);
        $this->_redirect('/admin/delivery');
    }

    /**
     * Переход при успешном изменении объекта.
     * @param $entity
     */
    protected function redirectWhenSuccess($entity = null)
    {
        $this->_flashMessenger->addMessage('Delivery email updated.', Lib_Flash::NOTICE, Lib_Flash::LATER);
        $this->_redirect('/admin/delivery');
    }

    public function importAction()
    {
        $form = $this->getImportForm();
        $this->view->form = $form;
        if ($this->_request->isPost()) {
            if ($form->isValid($this->_getAllParams())) {
                $emailParser = new \Managers\EmailFileParser();
                try {
                    $parsedData = $emailParser->parse($form->getValue('file'));
                    $this->view->data = $parsedData;
                    $this->renderScript('/delivery/emails.phtml');
                } catch (LogicException $e) {
                    $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::NOW);
                } catch (Exception $e) {
                    $this->handleException($e);
                }
            }
        }
    }

    public function saveAction()
    {
        if ($this->_request->isPost()) {
            try {
                $this->manager->saveImports($this->_getParam('email'));
                $this->_flashMessenger->addMessage('Email addresses successfully imported.', Lib_Flash::NOTICE, Lib_Flash::LATER);
                $this->_redirect('/admin/delivery');
            } catch (LogicException $e) {
                $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::LATER);
            } catch (Exception $e) {
                $this->handleException($e);
            }
        }
        $this->_redirect('/admin/delivery/import');

    }

    private function getImportForm()
    {
        $formBuilder = \G4T\Form\FormBuilder::createFormBuilder(\Managers\DeliveryEmail::TABLE)
            ->addField('file', 'file', array('label' => 'Import file'))
            ->addField('submit', 'submit', array('label' => 'Import', 'class' => 'btn btn-primary'));
        return $formBuilder->getForm();
    }
}

